import mongoClient from "../db/mongo/index.js";

const dbName = process.env.MONGO_DB_COLLECTION_NAME;
const db = mongoClient.db(dbName);
const messageCollection = db.collection("gw_chat");

// 保存聊天消息（未读）
export async function saveMessage(message) {
  try {
    const result = await messageCollection.insertOne(message);
    if (result.insertedId) {
      return true;
    } else {
      return false;
    }
  } catch (error) {
    console.log(error);
    throw error;
  }
}

// 删除聊天消息（未读）
export async function deleteMessages(messageIds) {
  try {
    const result = await messageCollection.deleteMany({
      _id: { $in: messageIds },
    });
    if (result.deletedCount) {
      return true;
    } else {
      return false;
    }
  } catch (error) {
    console.log(error);
    throw error;
  }
}

// 获取聊天消息（未读）
export async function getUnreadMessages(userId) {
  try {
    const result = await messageCollection.find({ receiver: userId }).toArray();
    return result;
  } catch (error) {
    console.log(error);
    throw error;
  }
}
